<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Manu;
use App\Http\Services\BaseService;
use Illuminate\Support\Facades\DB;

class ManuService extends BaseService
{
    /*
     * 厂家采集
     * */
    public function store($attributes = [])
    {
        if(empty($attributes)){
            throw new InvalidRequestException('参数错误 不能为空');
        }
        if(!is_array($attributes)){
            $attributes = json_decode($attributes,true);
        }

        if(!empty($attributes)){
            foreach ($attributes as $item){
                if(!empty($item['manu_no'])){
                    $tmp = [
                        'manu_no' => $item['manu_no'],
                        'manu_name' => $item['manu_name']
                    ];
                    //因为数量不多 所以直接循环判断
                    if(Manu::where('manu_no',$item['manu_no'])->exists()){
                        Manu::where('manu_no',$item['manu_no'])->update($tmp);
                    }else{
                        Manu::create($tmp);
                    }
                }
            }
        }

        return true;
    }

    public function data($attributes = []){

        $query  =   DB::table('admin_manus');
        if(!empty($attributes)){
            $query  =   $query->where('manu_name','like',"%$attributes%")
            ->orWhere('manu_no','like',"%$attributes%");
        }
        $query  =   $query->get();

        return $query;
    }

}
